<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\lib\exception\BaseException;
use app\middleware\admin\Auth;
use app\model\Admins;
use app\model\Role;
use app\model\Rule;

class Admin extends BaseController
{
    protected $middleware = [Auth::class];

    /**
     * 菜单
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getinfo()
    {
        $role = Admins::with('role')->find(request()->userid);
        if ($role->role_id == 1) {
            $menu = Rule::where('is_menu', 1)->where('status',1)->order('sort', 'desc')->select();
            $authority=Rule::where('status',1)->where('is_menu',0)->column('path');
        } else {
            $rule = Role::find($role->role_id);
            $menu = Rule::where('is_menu', 1)->where('status',1)->order('sort', 'desc')->whereIn('id', $rule->rule_id)->select();
            $authority=Rule::where('is_menu', 0)->where('status',1)->order('sort', 'desc')->whereIn('id', $rule->rule_id)->column('path');
        }
        $role['menu']=getTree($menu);
        $role['rule']=$authority;
        return $this->success($role);
    }

    public function index($limit = 10)
    {
        $roles= Role::select();
        $keyword=request()->param('keyword');
        $data=Admins::with('role')->when($keyword,function($query) use($keyword){
            $query->where('username','like','%'.$keyword.'%');
        })->paginate($limit);

        return $this->success(compact('data','roles'));
    }

    public function create()
    {
        return $this->success(Admins::create(request()->param()));
    }

    public function update()
    {
        $params = request()->param();

        if (!empty($params['password'])) {
            $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
        }
        $model = Admins::where('id', $params['id']);
        unset($params['id']);
        return $this->success($model->update($params));
    }

    public function updatepwd()
    {
        $params = request()->param();
        if (!empty($params['password'])) {
            $params['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
        }
        $model = Admins::where('id', request()->userid)->update($params);
        return $this->success();
    }

    public function del($id)
    {
       return $this->success(Admins::where('id',$id)->delete());
    }
}
